package com.file;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class FileApp1 {
    public static void main(String[] args) {

                String imagePath = "D:\\FileIo\\panda.png";

                try (FileInputStream imageInputStream = new FileInputStream(imagePath)) {
                    // 读取图片字节数据

                    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int bytesRead;

                    while ((bytesRead = imageInputStream.read(buffer)) != -1) {
                        byteOutputStream.write(buffer, 0, bytesRead);
                    }

                    byte[] imageBytes = byteOutputStream.toByteArray();

                    // Base64编码
                    String base64Image = Base64.getEncoder().encodeToString(imageBytes);

                    // 输出结果
                    System.out.println("Base64编码后的图片内容:\n" + base64Image);
                    //
                    File desFileName = new File("D:" + File.separator + "FileIo" + File.separator + "2016024.txt");

                    if (!desFileName.exists()) {
                        desFileName.createNewFile();

                    }
                    FileOutputStream desFile = new FileOutputStream(desFileName);
                    desFile.write(base64Image.getBytes(StandardCharsets.UTF_8));
                    System.out.println("写入完成");

                } catch (FileNotFoundException e) {
                    System.err.println("图片未找到: " + e.getMessage());
                } catch (IOException e) {
                    System.err.println("读取图片时发生错误: " + e.getMessage());
                }

    }
}
